<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

// 为方便系统核心升级，二次开发中需要用到的公共函数请写在这个文件，不要去修改common.php文件

/**
 * @abstract json 数据格式的输出
 * @param number $code
 * @param string $msg
 * @param array $data
 * return json
 */
if (!function_exists('json_out')) {
	function json_out($code = 200, $msg = '', $data = []) {
		Debug::remark('all-end');
	    header('Content-Type:application/json; charset=utf-8');
		//跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
	    $result = array(
	        'code' => $code,
			'msg'  => (string)$msg,
			'debug'	=> think\facade\Debug::getRangeTime('all-begin','all-end').'s',
	        'data' => $data,
	    );
	    echo json_encode($result, JSON_UNESCAPED_UNICODE);
	    exit;
	}
}

/**
 * @abstract 缓存层调用
 * @param string $name
 * @param object 对象
 * return json
 */
if (!function_exists('datacache')) {
	function datacache($name) {
	    return controller($name, 'datacache');
	}
}

/**
 * @abstract 数组数据格式的输出
 * @param number $code
 * @param string $message
 * @param array  $data
 */
if (!function_exists('array_out')) {
    function array_out($code = 200, $message = '', $data = []) {
        $result = [
            'code'      => $code,
            'message'   => (string)$message,
            'data'      => $data,
        ];

        return $result;
    }
}



/**
 * @abstract 友好的时间显示
 * @param int    $sTime 时间戳
 * @return string
 *
 */
if (!function_exists('friendly_date')) {
	function friendly_date($posttimes) {
	    //当前时间的时间戳
	    $nowtimes = strtotime(date('Y-m-d H:i:s'),time());
	    //之前时间参数的时间戳
	    $posttimes = $posttimes;
	    //相差时间戳
	    $counttime = $nowtimes - $posttimes;
	    //进行时间转换
	    if($counttime<=60){
	       return '刚刚';
	    }else if($counttime>60 && $counttime<3600){
	       return intval(($counttime/60)).'分钟前';
	    }else if($counttime>=3600 && $counttime<3600*24){
	       return intval(($counttime/3600)).'小时前';
	    }else if($counttime>=3600*24 && $counttime<3600*24*2){
	       return '昨天';
	    }else if($counttime>=3600*24*2 && $counttime<=3600*24*30){
	       return intval(($counttime/(3600*24))).'天前';
	    }else if($counttime>=3600*24*30 && $counttime<=3600*24*30*36){
	        return intval(($counttime/(3600*24*30))).'个月前';
	    }else{
	       return date('Y-m-d H:i',$posttimes);
	    }
	}
}

/**
 * @abstract 生成token
 * @param number $code
 * @param string $message
 * @param array  $data
 */
if (!function_exists('create_authtoken')) {
    function create_authtoken($uid) {
        //生成
        $result = [];
    	$result['access_token_expire_in']   = config('access_token_expire_time');//config();
		$result['access_token_expire_time'] = time() + $result['access_token_expire_in'];//到期时间
    	$result['access_token'] 			= base64_encode(md5($uid.microtime().$result['access_token_expire_time'].config('access_token_key')));
    	$result['refresh_token_expire_in']   = config('refresh_token_expire_time');//config();
		$result['refresh_token_expire_time'] = time() + $result['refresh_token_expire_in'];//到期时间
    	$result['refresh_token'] 			 = base64_encode(md5($uid.microtime().$result['refresh_token_expire_in'].config('refresh_token_key')));
        return $result;
    }
}

/**
 * @abstract 旧手机验证TOKEN
 * @param number $mobile
 * @param string $code
 * @param array  $data
 */
if (!function_exists('mboile_old_token')) {
    function mboile_old_token($uid, $mobile, $code) {
        //生成
        $result = [];
    	$result['mobile_token']   = base64_encode(md5($uid.microtime().$mobile.$code));
        return $result;
    }
}

/**
 * @abstract 数字友好
 * @param int $num
 * @return string
 */
if (!function_exists('num_friendly')) {
	function num_friendly($num){
	    if($num < 1000) {
	       return $num;
	    } else if($num >=1000 && $num < 10000){
	       return round($num/1000,1).'k';
	    } else if ($num >= 10000) {
	       return round($num/10000,2).'w';
	    }
	}
}

/**
 * @abstract 对象 to 数组
 * @param object object
 * @return array
 */
if (!function_exists('object2array')) {
	function object2array(&$object) {
		$object =  json_decode( json_encode( $object),true);
		return  $object;
	}
}

/** 
 *      把秒数转换为时分秒的格式 
 *      @param Int $times 时间，单位 秒 
 *      @return String 
 */
if (!function_exists('times')) {
	function secToTime($times){  
		$result = '00:00:00';  
		if ($times>0) {  
				$hour = floor($times/3600);  
				$minute = floor(($times-3600 * $hour)/60);  
				$second = floor((($times-3600 * $hour) - 60 * $minute) % 60);  
				$result = sprintf("%02d",$hour).':'.sprintf("%02d",$minute).':'.sprintf("%02d",$second);  
		}  
		return $result;  
	}
}

/** 
 *      把B 转换KB MB GB TB
 *      @param Int $times 时间，单位 秒 
 *      @return String 
 */
if (!function_exists('formatBytes')) {
	function formatBytes($size) {

		$units = array(' B', ' KB', ' MB', ' GB', ' TB');

		for ($i = 0; $size >= 1024 && $i < 4; $i++) {

			$size /= 1024;

		}
		return round($size, 2).$units[$i];

	}
}

/**
 * @abstract 计算年龄
 * @param int $birthday 生日
 * @return string
 */
if (!function_exists('getAge')) {
	function getAge($birthday){
		$age = '';
		if($birthday){
			//格式化出生时间年月日
			$byear	= date('Y', $birthday);
			$bmonth	= date('m', $birthday);
			$bday	= date('d', $birthday);
			
			//格式化当前时间年月日
			$tyear	= date('Y');
			$tmonth	= date('m');
			$tday  	= date('d');
			
			//开始计算年龄
			$age = $tyear - $byear;
			if($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday){
				$age--;
			}
		}
		
		return $age;
	}
}


/**
 * @abstract 行为封装
 * @param int $birthday 生日
 * @return string
 */
if (!function_exists('logic_hook')) {
	function logic_hook($action, $params, $hook_type){
		$register_pre_rel = \think\facade\Hook::listen($action.'_'.$hook_type, $params);
		foreach ($register_pre_rel as $key => $value) {
			if( $value['code'] < 0 ) return array_out(-1001, $value['message']);
		}
		return array_out(200, 'success');
	}
}


/**
    *
    *接收头信息
 **/
function em_getallheaders() {
   foreach ($_SERVER as $name => $value)
   {
	   if (substr($name, 0, 5) == 'HTTP_')
	   {
		   $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
	   }
   }
   return $headers;
}

/**
 * @abstract 获取用户头像
 * @param int $birthday 生日
 * @return string
 */
if (!function_exists('get_avatar_user')) {
	function get_avatar_user($uid, $size = 'middle') {
		//$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
		/* $uid = abs(intval($uid)); //UID取整数绝对值
		$uid = sprintf("%09d", $uid); //前边加0补齐9位，例如UID为31的用户变成 000000031
		$dir1 = substr($uid, 0, 3);  //取左边3位，即 000
		$dir2 = substr($uid, 3, 2);  //取4-5位，即00
		$dir3 = substr($uid, 5, 2);  //取6-7位，即00
		//下面拼成用户头像路径，即000/00/00/31_avatar_middle.jpg
		$url = $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2)."_avatar.jpg"; */
		//查询数据库是否存在头像
		$rel = model('user_center/Member', 'model\user') -> getDateByUid($uid, false);
		//dump($rel);
		if($rel['code'] == 200 && $rel['data']->avatar_url != '' && $rel['data']->avatar_url != null){
			$result = $rel['data']->avatar_url;
		}else{
			$result = "http://oss.mushop.live/avator/avatar_none.png?x-oss-process=image/resize,m_pad,h_500,w_500,color_cccccc";
			//$result = '';
		}
		/* $timeout = 3600*24*30;
		$cache_name = 'get_avatar_user_'.$uid;
		if(!\think\facade\Cache::get($cache_name)){
			$rel_url = controller('common/Osslogic', 'logic') -> getUrl('avator/'.$url, $timeout);
			if($rel_url['code'] == 200){
				$result = $rel_url['data'];
				
			}else{
				$rel_url = controller('common/Osslogic', 'logic') -> getUrl('avator/timg.jpg', $timeout);//dump($rel_url);
				$result = $rel_url['data'];
			}

			//缓存
			\think\facade\Cache::set($cache_name, $result, $timeout);
		}
		$result = \think\facade\Cache::get($cache_name); */
		return $result;
	}

}	

/**
 * @abstract 获取用户头像 oss路径规则
 * @param int $birthday 生日
 * @return string
 */
if (!function_exists('get_avatar_user_path')) {
	function get_avatar_user_path($uid, $size = 'middle') {
		//$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
		$uid_t = abs(intval($uid)); //UID取整数绝对值
		$uid_t = sprintf("%09d", $uid_t); //前边加0补齐9位，例如UID为31的用户变成 000000031
		$dir1 = substr($uid_t, 0, 3);  //取左边3位，即 000
		$dir2 = substr($uid_t, 3, 2);  //取4-5位，即00
		$dir3 = substr($uid_t, 5, 2);  //取6-7位，即00
		//下面拼成用户头像路径，即000/00/00/31_avatar_middle.jpg
		return $url = 'avator/'.$dir1.'/'.$dir2.'/'.$dir3.'/'.$uid."_avatar.jpg";
	}
}


/**
 * @abstract 获取视频封面图 oss路径规则
 * @param int $cover_url 封面图本地路径
 * @return string
 */
if (!function_exists('get_cover_pic_path')) {
    function get_cover_pic_path($cover_url, $size = 'middle') {
        //下面拼成封面图路径，即cover/18051597198640_cover.jpg
        return $url = 'cover/'.$cover_url;
    }
}
/**
 * @abstract 获取阿里云图片链接 oss路径规则
 * @param int $cover_url 图片本地路径
 * @return string
 */
if (!function_exists('get_aliyun_pic_path')) {
    function get_aliyun_pic_path($file_path_id,$path = '', $size = 'middle') {
        //获取本地路径
        $file_path = model('admin/Attachment') -> getFilePath($file_path_id, 1);
        //下面拼成封面图路径，即pics/uploads/....jpg
        $aliyun_url = $path.$file_path;
        //上传OSS
        $rel = controller('common/Osslogic', 'logic') -> uploadFile($file_path, $aliyun_url);
        if($rel['code'] == '200'){
            //删除本地附件
            if($rel['data']['info']['url'] > 0) controller('common/Attachmentlogic', 'logic') -> delete($file_path_id);
        }
        return $rel;
    }
}


	/**
	 * @abstract 表单验证token创建
	 * @return string
	 */
	if (!function_exists('create_token')) {	
		//创建TOKEN
		function form_create_token() {
		   $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) .       chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
		   session('TOKEN', form_auth_code($code));
		}
	}
	
	/**
	 * @abstract 表单TOKEN验证
	 * @return string
	 */
	if (!function_exists('form_check_token')) {
		//判断TOKEN
		function form_check_token($token) {
			if ($token == session('TOKEN')) {
			   session('TOKEN', NULL);
			   return TRUE;
			} else {
			  return FALSE;
			}
		}
	}
	
	/**
	 * @abstract 加密TOKEN 
	 * @return string
	 */
	if (!function_exists('form_auth_code')) {
		function form_auth_code($str) {
			$key = "YOURKEY";
			$str = substr(md5($str), 8, 10);
			return md5($key . $str);
		}
	}

/**
 * @abstract 获取用户头像
 * @param int $birthday 生日
 * @return string
 */
if (!function_exists('get_round_username')) {
	function get_round_username() {
		$tou=array('快乐','冷静','醉熏','潇洒','糊涂','积极','冷酷','深情','粗暴','温柔','可爱','愉快','义气','认真','威武','帅气','传统','潇洒','漂亮','自然','专一','听话','昏睡','狂野','等待','搞怪','幽默','魁梧','活泼','开心','高兴','超帅','留胡子','坦率','直率','轻松','痴情','完美','精明','无聊','有魅力','丰富','繁荣','饱满','炙热','暴躁','碧蓝','俊逸','英勇','健忘','故意','无心','土豪','朴实','兴奋','幸福','淡定','不安','阔达','孤独','独特','疯狂','时尚','落后','风趣','忧伤','大胆','爱笑','矮小','健康','合适','玩命','沉默','斯文','香蕉','苹果','鲤鱼','鳗鱼','任性','细心','粗心','大意','甜甜','酷酷','健壮','英俊','霸气','阳光','默默','大力','孝顺','忧虑','着急','紧张','善良','凶狠','害怕','重要','危机','欢喜','欣慰','满意','跳跃','诚心','称心','如意','怡然','娇气','无奈','无语','激动','愤怒','美好','感动','激情','激昂','震动','虚拟','超级','寒冷','精明','明理','犹豫','忧郁','寂寞','奋斗','勤奋','现代','过时','稳重','热情','含蓄','开放','无辜','多情','纯真','拉长','热心','从容','体贴','风中','曾经','追寻','儒雅','优雅','开朗','外向','内向','清爽','文艺','长情','平常','单身','伶俐','高大','懦弱','柔弱','爱笑','乐观','耍酷','酷炫','神勇','年轻','唠叨','瘦瘦','无情','包容','顺心','畅快','舒适','靓丽','负责','背后','简单','谦让','彩色','缥缈','欢呼','生动','复杂','慈祥','仁爱','魔幻','虚幻','淡然','受伤','雪白','高高','糟糕','顺利','闪闪','羞涩','缓慢','迅速','优秀','聪明','含糊','俏皮','淡淡','坚强','平淡','欣喜','能干','灵巧','友好','机智','机灵','正直','谨慎','俭朴','殷勤','虚心','辛勤','自觉','无私','无限','踏实','老实','现实','可靠','务实','拼搏','个性','粗犷','活力','成就','勤劳','单纯','落寞','朴素','悲凉','忧心','洁净','清秀','自由','小巧','单薄','贪玩','刻苦','干净','壮观','和谐','文静','调皮','害羞','安详','自信','端庄','坚定','美满','舒心','温暖','专注','勤恳','美丽','腼腆','优美','甜美','甜蜜','整齐','动人','典雅','尊敬','舒服','妩媚','秀丽','喜悦','甜美','彪壮','强健','大方','俊秀','聪慧','迷人','陶醉','悦耳','动听','明亮','结实','魁梧','标致','清脆','敏感','光亮','大气','老迟到','知性','冷傲','呆萌','野性','隐形','笑点低','微笑','笨笨','难过','沉静','火星上','失眠','安静','纯情','要减肥','迷路','烂漫','哭泣','贤惠','苗条','温婉','发嗲','会撒娇','贪玩','执着','眯眯眼','花痴','想人陪','眼睛大','高贵','傲娇','心灵美','爱撒娇','细腻','天真','怕黑','感性','飘逸','怕孤独','忐忑','高挑','傻傻','冷艳','爱听歌','还单身','怕孤单','懵懂');
		$do = array("的","爱","","与","给","扯","和","用","方","打","就","迎","向","踢","笑","闻","有","等于","保卫","演变");
		$biaoqing = array("😂","😊","☝","👦","🐵","🐒","🦍","🦊","方","打","就","迎","向","踢","笑","闻","有","等于","保卫","演变");
        $wei=array('嚓茶','凉面','便当','毛豆','花生🥜','可乐','灯泡','哈密瓜','野狼','背包','眼神','缘分','雪碧','人生','牛排','蚂蚁','飞鸟','灰狼','斑马','汉堡','悟空','巨人','绿茶','自行车','保温杯','大碗','墨镜','魔镜','煎饼','月饼','月亮','星星','芝麻','啤酒','玫瑰','大叔','小伙','哈密瓜，数据线','太阳','树叶','芹菜','黄蜂','蜜粉','蜜蜂','信封','西装','外套','裙子','大象','猫咪','母鸡','路灯','蓝天','白云','星月','彩虹','微笑','摩托','板栗','高山','大地','大树','电灯胆','砖头','楼房','水池','鸡翅','蜻蜓','红牛','咖啡','机器猫','枕头','大船','诺言','钢笔','刺猬','天空','飞机','大炮','冬天','洋葱','春天','夏天','秋天','冬日','航空','毛衣','豌豆','黑米','玉米','眼睛','老鼠','白羊','帅哥','美女','季节','鲜花','服饰','裙子','白开水','秀发','大山','火车','汽车','歌曲','舞蹈','老师','导师','方盒','大米','麦片','水杯','水壶','手套','鞋子','自行车','鼠标','手机','电脑','书本','奇迹','身影','香烟','夕阳','台灯','宝贝','未来','皮带','钥匙','心锁','故事','花瓣','滑板','画笔','画板','学姐','店员','电源','饼干','宝马','过客','大白','时光','石头','钻石','河马','犀牛','西牛','绿草','抽屉','柜子','往事','寒风','路人','橘子','耳机','鸵鸟','朋友','苗条','铅笔','钢笔','硬币','热狗','大侠','御姐','萝莉','毛巾','期待','盼望','白昼','黑夜','大门','黑裤','钢铁侠','哑铃','板凳','枫叶','荷花','乌龟','仙人掌','衬衫','大神','草丛','早晨','心情','茉莉','流沙','蜗牛','战斗机','冥王星','猎豹','棒球','篮球','乐曲','电话','网络','世界','中心','鱼','鸡','狗','老虎','鸭子','雨','羽毛','翅膀','外套','火','丝袜','书包','钢笔','冷风','八宝粥','烤鸡','大雁','音响','招牌','胡萝卜','冰棍','帽子','菠萝','蛋挞','香水','泥猴桃','吐司','溪流','黄豆','樱桃','小鸽子','小蝴蝶','爆米花','花卷','小鸭子','小海豚','日记本','小熊猫','小懒猪','小懒虫','荔枝','镜子','曲奇','金针菇','小松鼠','小虾米','酒窝','紫菜','金鱼','柚子','果汁','百褶裙','项链','帆布鞋','火龙果','奇异果','煎蛋','唇彩','小土豆','高跟鞋','戒指','雪糕','睫毛','铃铛','手链','香氛','红酒','月光','酸奶','银耳汤','咖啡豆','小蜜蜂','小蚂蚁','蜡烛','棉花糖','向日葵','水蜜桃','小蝴蝶','小刺猬','小丸子','指甲油','康乃馨','糖豆','薯片','口红','超短裙','乌冬面','冰淇淋','棒棒糖','长颈鹿','豆芽','发箍','发卡','发夹','发带','铃铛','小馒头','小笼包','小甜瓜','冬瓜','香菇','小兔子','含羞草','短靴','睫毛膏','小蘑菇','跳跳糖','小白菜','草莓','柠檬','月饼','百合','纸鹤','小天鹅','云朵','芒果','面包','海燕','小猫咪','龙猫','唇膏','鞋垫','羊','黑猫','白猫','万宝路','金毛','山水','音响','尊云','西安');
        $tou_num=rand(0,331);
        $do_num=rand(0,19);
        $wei_num=rand(0,327);
        $type = rand(0,1);
        if($type==0){
        $username=$tou[$tou_num].$do[$do_num].$wei[$wei_num];
        }else{
        $username=$wei[$wei_num].$tou[$tou_num];
		}
		
		return $username;
	}
}

if (!function_exists('curl_request')) {

    //可以发送get和post的请求方式
    function curl_request($url, $method = 'get', $data = null, $https = true, $referer ='', $headers = [], $useragent= '') {
        //1.初识化curl
        $ch = curl_init($url);
        //2.根据实际请求需求进行参数封装
        //返回数据不直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		curl_setopt($ch, CURLOPT_URL, $url);
		//头部
		if($headers){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		}
        //curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);  // timeout设为1秒     
        //如果是https请求
        if ($https === true) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        //如果是post请求
        if ($method === 'post') {
            //开启发送post请求选项
            curl_setopt($ch, CURLOPT_POST, true);
            //发送post的数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		}
		
		// 模拟来源
		if($referer){
			curl_setopt($ch, CURLOPT_REFERER, $referer);
		}

		//模拟浏览器
		if($useragent){
			curl_setopt($ch, CURLOPT_USERAGENT, $useragent); //模拟常用浏览器的useragent
		}
        //3.发送请求
        $result = curl_exec($ch);
        //4.返回返回值，关闭连接
        curl_close($ch);
        return $result;
	}
	
}

/**
 * @abstract 多维数组根据某个字段去重
 * @param array $arr 数组
 * * @param string $key 字段值
 * @return array
 */
if (!function_exists('array_unset_tt')) {
	function array_unset_tt($arr, $key='playId'){
		//建立一个目标数组
		$res = array();
		foreach ($arr as $value) {
			//查看有没有重复项
			if(isset($res[$value[$key]])){
				unset($value[$key]);  //有：销毁
			}else{
				$res[$value[$key]] = $value;
			}
		}
		return $res;
	}
}

/**
 * @abstract 数组随机
 * @param array $arr 数组
 * @param int $num 生成数组数量
 * @return array
 */
if (!function_exists('array_rand_tt')) {
	function array_rand_tt($arr, $num = 1){
		//建立一个目标数组
		$res = [];
		$arr_count = count($arr);
		if($arr_count > 1){
			if($arr_count >= $num){
				$rand_num = array_rand($arr, $num);
				if(is_array($rand_num)){
					$res = $rand_num;
				}else{
					$res[] = $rand_num;
				}
			}else{ //数组数量 小于 需要随机获取的数量
				$res = $arr;
			}
		}else{
			$keys = array_keys($arr);
			$res[] = $keys[0];
		}
		return $res;
	}
}

/**
 * @abstract 举报
 * @param array $arr 数组
 * @param int $num 生成数组数量
 * @return array
 */
if (!function_exists('play_report')) {
	function play_report(){
		$result_list = [
			[
				'title' => '内容违规',
				'report_type' => [
					['id' => 1, 'name' => '色情低俗'],
					['id' => 2, 'name' => '政治敏感'],
					['id' => 3, 'name' => '违法犯罪'],
					['id' => 4, 'name' => '垃圾广告、售卖假货等'],
					['id' => 5, 'name' => '侮辱谩骂'],
					['id' => 6, 'name' => '非原创内容'],
				]
			],
			[
				'title' => '侵权',
				'report_type' => [
					['id' => 7, 'name' => '侵犯权益'],
				]
			],
			[
				'title' => '未成年',
				'report_type' => [
					['id' => 8, 'name' => '未成年人不当行为'],
					['id' => 9, 'name' => '内容不适合未成年人观看'],
				]
			],
			[
				'title' => '其他',
				'report_type' => [
					['id' => 10, 'name' => '引人不适'],
					['id' => 11, 'name' => '疑似自我伤害'],
					['id' => 12, 'name' => '诱导点赞、分享、关注'],
					['id' => 13, 'name' => '其他'],
				]
			],
		];
		
		return $result_list;
	}
}

if (!function_exists('get_warehouse_type')) {
    /**
     * 获取仓库类型   联动获取-门店使用
     * @param ty 	                int  仓库类别（1：分仓；2：总仓）
     * @param store_id 	            int  门店id
     * @author dou <51779987@qq.com>
     */
    function get_warehouse_type($ty=false,$store_id=false)
    {
        $arr = [];
        //获取数据
        if($ty){
            if($store_id){
                //查找数据,排除已使用过
                $list_warehouse_data = model('ErpStoreWarehouse','model')->clearUp($store_id,$ty);
                if(!empty($list_warehouse_data['data'])){
                    $list_warehouse = $list_warehouse_data['data'];
                }
            }else{
                //查找所有数据
                if($ty < 1000){
                    $list_warehouse = model('ErpWarehouse','model')->where('type', '=', $ty)->field('id,title,type')->order('sort', 'asc')->select();
                }else{
                    $list_warehouse = model('ErpWarehouse','model')->field('id,title,type')->order('sort', 'asc')->select();
                }

            }
            if(!empty($list_warehouse)){
                foreach ($list_warehouse as $key => $value){
                    $arr[$key]['id']    = (int)$value['id'];
                    $arr[$key]['title'] = (string)$value['title'];
                    $arr[$key]['type']  = (int)$value['type'];
                }
            }
            return $arr;
        }else{
            /*if ($this->request->isPost()) {
                //分仓总仓二级联动获取
                //数据接收
                $data = $this->request->post('', null, 'trim');
                //查找数据
                $list_warehouse = ErpWarehouse::where('type', '=', $data['type'])->field('id,title,type')->order('sort', 'asc')->select();
                $arr['code'] = '1'; //判断状态
                $arr['msg'] = '请求成功'; //回传信息
                $arr['list'] = [];
                foreach ($list_warehouse as $key => $value){
                    $arr['list'][] = ['key' => $value['id'], 'value' => $value['title']];
                }
                return json($arr);
            }*/
        }
        return isset($arr) ? $arr : '';
    }
}

if (!function_exists('get_nick_name')) {
    /**
     * 根据自动获取名字
     * @param ty 	                int  类型（全返回or返回字段）
     * @param table 	            string  表名
     * @param surf 	                string  查询字段名
     * @param surf_k 	            string  查询字段值
     * @param surf_s 	            string  返回内容
     * @author dou <51779987@qq.com>
     */
    function get_nick_name($ty=false,$table,$surf,$surf_v,$surf_s)
    {
        $arr = [];
        $map = [];//搜索处理
        if($surf != '')          $map[] = [$surf, '=',$surf_v ];
        //获取数据
        $res = model($table,'model')->where($map)->find();
        if($ty){
            $arr = $res[$surf_s];
        }
        return isset($arr) ? $arr : '';
    }
}

if (!function_exists('getAround')) {
    /*

	* 计算经纬度范围

	* $lat 纬度

	* $lon 经度

	* $raidus 半径(米)

	*/
	function getAround($lat, $lon, $raidus) {
		$PI = 3.14159265;
		$EARTH_RADIUS = 6378137;
		$RAD = $PI / 180.0;
		$latitude = $lat;
		$longitude = $lon;
		$degree = (24901 * 1609) / 360.0;
		$raidusMile = $raidus;
		$dpmLat = 1 / $degree;
		$data = array();
		$radiusLat = $dpmLat * $raidusMile;
		$minLat = $latitude - $radiusLat;
		$maxLat = $latitude + $radiusLat;
		$data["maxLat"] = $maxLat;
		$data["minLat"] = $minLat;
		$mpdLng = $degree * cos($latitude * ($PI / 180));
		$dpmLng = 1 / $mpdLng;
		$radiusLng = $dpmLng * $raidusMile;
		$minLng = $longitude - $radiusLng;
		$maxLng = $longitude + $radiusLng;
		$data["maxLng"] = $maxLng;
		$data["minLng"] = $minLng;
		//print_r($data);
		return $data;

	}

if (!function_exists('getdistance')) {	
	/**
	 * 求两个已知经纬度之间的距离,单位为米
	 * 
	 * @param lon1 $ ,lon2 经度
	 * @param lat1 $ ,lat2 纬度
	 * @return float 距离，单位米
	 * @author shiqiang
	 */
	function getdistance($lon1, $lat1, $lon2, $lat2) {
		$earthRadius = 6367000; //approximate radius of earth in meters 
        $lat1 = ($lat1 * pi() ) / 180; 
        $lon1 = ($lon1 * pi() ) / 180; 
        $lat2 = ($lat2 * pi() ) / 180;
        $lon2 = ($lon2 * pi() ) / 180; 
		
        $calcLongitude = $lon2 - $lon1; 
        $calcLatitude  = $lat2 - $lat1; 
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lon1) * cos($lon2) * pow(sin($calcLongitude / 2), 2); 
        $stepTwo = 2 * asin(min(1, sqrt($stepOne))); 
        $calculatedDistance = $earthRadius * $stepTwo; 
        return round($calculatedDistance); 
	} 
}	
	
}

if (!function_exists('factory')) {

    /**
     * 
     * 工厂模式调用
     * @Return: array
     */
    function factory($model, $level = '') {
        
        $obj = 'app\\erp\\designpattern\\'.$level.'\\'.$model;
        $model = new $obj;

        return $model;
    }

}


if (!function_exists('useCurl')) {
    function useCurl($url,$data,$second=60) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $second);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);   // 异步调用时需要添加这一行
        $output = curl_exec($ch);
        curl_close($ch);
    }
}


/**
 * 日志打印
 */
if (!function_exists('write_log')) {
    function write_log($data)
    {
        $years = date('Y-m');
        //设置路径目录信息
        $url = 'log/txlog/' . $years . '/' . date('Ymd') . '_request_log.txt';
        $dir_name = dirname($url);
        //目录不存在就创建
        if (!file_exists($dir_name)) {
            //iconv防止中文名乱码
            $res = mkdir(iconv("UTF-8", "GBK", $dir_name), 0777, true);
        }
        $fp = fopen($url, "a");//打开文件资源通道 不存在则自动创建
        fwrite($fp, date("Y-m-d H:i:s") . var_export($data, true) . "\r\n");//写入文件
        fclose($fp);//关闭资源通道
    }
}


/**
 * 自动发放优惠券
 */
if (!function_exists('auto_receive_coupon')) {
    function auto_receive_coupon($uid, $rule_type)
    {
		// config('coupon_rule_type_zd');
		// 0注册  1消费
        //注册成功 发放优惠券
		$map = [];
		$map['coupon_rule'] 		= 0;
		$map['coupon_rule_type'] 	= $rule_type;
		$coupon_rule = model('erp/ErpCouponRules', 'model') -> where($map) -> order('id desc') -> column('id,coupon_id,coupon_rule_period_num');//满足注册规则的优惠券id
		foreach($coupon_rule as $val){
            $coupon_id              = $val['coupon_id'];
            $coupon_rule_period_num = $val['coupon_rule_period_num'];

            $coupon_list = controller('erp/Couponlogic','logic') -> coupon_list($uid, $coupon_id);//可领取的优惠券列表
            if($coupon_list['code'] == 200 && !empty($coupon_list['data'])){
                $coupon_list = $coupon_list['data'];
                foreach($coupon_list as $value){
                    if($value['coupon_attribute'] == 1 && $value['coupon_attribute_num'] > 0){//可重复领取
                        for($i = 0; $i< $value['coupon_attribute_num']; $i++){
                            $rel = controller('erp/CouponUserinfologic','logic') -> coupon_receive($uid, $value['id'], 0);//发放优惠券
                            if($rel['code'] == 200 && $coupon_rule_period_num > 0){
                                $id = $rel['data'];
                                $map = [];
                                $map['id'] 			= $id;

                                $data = [];
                                $data['coupon_stime'] 		= time();
                                $data['coupon_etime']   	= time() + ($coupon_rule_period_num * 60 * 60 * 24);
                                $res = model('erp/ErpCouponUseinfo', 'model') -> update($data, $map);
                            }
                        }
                    }
                    if($value['coupon_attribute'] == 0){//不可重复领取，发放一张
                        $rel = controller('erp/CouponUserinfologic','logic') -> coupon_receive($uid, $value['id'], 0);//发放优惠券
                        if($rel['code'] == 200 && $coupon_rule_period_num > 0){
                            $id = $rel['data'];
                            $map = [];
                            $map['id'] 			= $id;

                            $data = [];
                            $data['coupon_stime'] 		= time();
                            $data['coupon_etime']   	= time() + ($coupon_rule_period_num * 60 * 60 * 24);
                            $res = model('erp/ErpCouponUseinfo', 'model') -> update($data, $map);
                        }
                    }
                }
            }
        }
    }
}

function rolling_curl($urls, $callback='', $custom_options = null)
{//多个url访问
 
    // make sure the rolling window isn't greater than the # of urls
    $rolling_window = 5;
    $rolling_window = (sizeof($urls) < $rolling_window) ? sizeof($urls) : $rolling_window;
 
    $master   = curl_multi_init();
    $curl_arr = array();
 
    // add additional curl options here
    $std_options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5
        );
    $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;
 
    // start the first batch of requests
    for ($i = 0; $i < $rolling_window; $i++) {
        $ch                   = curl_init();
        $options[CURLOPT_URL] = $urls[$i];
        curl_setopt_array($ch, $options);
        curl_multi_add_handle($master, $ch);
    }
	
	//如果是https请求
	//if ($https === true) {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	//}

    do {
        while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
        if ($execrun != CURLM_OK) {
            break;
        }
 
        // a request was just completed -- find out which one
        while ($done = curl_multi_info_read($master)) {
            $info = curl_getinfo($done['handle']);
			dump($info);
            if ($info['http_code'] == 200) {
                $output = curl_multi_getcontent($done['handle']);
				dump($output);
                // request successful.  process output using the callback function.
				//$callback($output);
				
                // start a new request (it's important to do this before removing the old one)
                // 当$i等于$urls数组大小时不用再增加了
                if($i<sizeof($urls)){
                    $ch                   = curl_init();
                    $options[CURLOPT_URL] = $urls[$i++]; // increment i
                    curl_setopt_array($ch, $options);
                    curl_multi_add_handle($master, $ch);
                }
                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $done['handle']);
            } else {
                // request failed.  add error handling.
            }
        }
    } while ($running);
 
    curl_multi_close($master);
    return true;
}
